package com.supcalls.service;

import com.supcalls.entity.Order;
import com.supcalls.feign.AccountClient;
import com.supcalls.feign.StorageClient;
import com.supcalls.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;

    @GlobalTransactional(name = "order-create", rollbackFor = Exception.class)
    public void createOrder(Order order) {
        log.info("创建订单: {}", order);
        order.setStatus(0);
        orderMapper.insert(order);

        // 扣减库存
        storageClient.decrease(order.getProductId(), order.getCount());

        // 扣减余额
        accountClient.decrease(order.getUserId(), order.getMoney());

        // 修改订单状态
        order.setStatus(1);
        orderMapper.updateById(order);
    }
}

